﻿using DryIoc;
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using StarryEdge.Core;
using StarryEdge.Core.Device;
using StarryEdge.Core.Enums;
using StarryEdge.Core.Manager;
using StarryEdge.Core.Parameter;
using StarryEdge.Model;
using StarryEdge.Parameter;
using StarryEdge.Views.Dialog;
using StarryEdge.WPF.Command;
using StarryEdge.WPF.Lang;
using StarryEdge.WPF.Models;
using StarryEdge.WPF.Resources.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;

namespace StarryEdge.ViewModels
{
    public class StatusBarViewModel : Prism.Mvvm.BindableBase
    {
        public ObservableCollection<LanguageImageModel> LangList { get; set; }
        public DateTime RunTime { get; set; }

        private string _versionNumber;

        public string VersionNumber
        {
            get { return _versionNumber; }
            set { SetProperty(ref _versionNumber, value); }
        }

        public TemporaryParameter Temporary { get; set; }
        private IEventAggregator _aggregator;
        private IContainerProvider _containerProvider;
        public StatusBarViewModel(ITemporaryParameter temporary, IEventAggregator aggregator, IContainerProvider containerProvider)
        {
            _containerProvider = containerProvider;
            _aggregator = aggregator;
            Temporary = (TemporaryParameter)temporary;
            RunTime = DateTime.Now;
            LangList = new ObservableCollection<LanguageImageModel>();
            UpdateLanguage();
            SetVersion();
            aggregator.GetEvent<MessageEvent>().Subscribe(sender => {
                UpdateLanguage();
            }, arg => arg.Code == 240);
            var deviceInfo = _containerProvider.Resolve<IDeviceInfoManage>();
        }

        private void SetVersion()
        {
            System.Reflection.AssemblyFileVersionAttribute[] obj = (System.Reflection.AssemblyFileVersionAttribute[])System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(System.Reflection.AssemblyFileVersionAttribute), false);
            VersionNumber = $"[{LangManager.Instance.Lang["SoftwareVersion"]} v {obj[0].Version} NET 6]";
        }

        public DelegateCommand<LanguageImageModel> LanguagePreviewMouseLeftButtonUp => new DelegateCommand<LanguageImageModel>(sender =>
        {
            if (sender != null)
            {
                LangManager.SetLang(sender.Lang);
                SetVersion();
                Temporary?.UpdateProperty();
                MessageEventModel message = new MessageEventModel
                {
                    Code = 210,
                    Message = "LangUpdate",
                };
                _aggregator.GetEvent<MessageEvent>().Publish(message);
            }
        });

        private void OpenDeviceList()
        {
            MessageEventModel message = new MessageEventModel
            {
                Code = 220,
                Message = "DeviceSystem_DeviceList",
            };
            _aggregator.GetEvent<MessageEvent>().Publish(message);
        }

        public RoleDelegateCommand Run => new RoleDelegateCommand(async () =>
        {
            var deviceInfo = _containerProvider.Resolve<IDeviceInfoManage>();
            if (deviceInfo.GetDevices().Any(x => x.IsOnline == false && x.Index != 999))
            {
                await _containerProvider.Resolve<IDialogHost>().DialogShow(LangManager.Instance.ToolTip["DeviceCommunicationFailure"], Core.Enums.LogLevel.Error);
                OpenDeviceList();
                return;
            }
            var taskManager = _containerProvider.Resolve<ITaskManager>();
            if (!Temporary.Status_Software)
            {
                _ = DialogHost.Show(new LoadingPopup(), PopUpTypes.Global.ToString());
                var device = _containerProvider.Resolve<IDeviceFactory>();
                if (await device.Connect())
                {
                    taskManager.LoopTask();
                }
                else
                {
                    await _containerProvider.Resolve<IDialogHost>().DialogShow(LangManager.Instance.ToolTip["DeviceCommunicationFailure"], Core.Enums.LogLevel.Error);
                    OpenDeviceList();
                }
                if (DialogHost.IsDialogOpen(PopUpTypes.Global.ToString()))
                {
                    DialogHost.Close(PopUpTypes.Global.ToString());
                }
            }
            else
            {
                taskManager.StopTask();
            }

        }, "SystemBottom", "StatusSoftware");

        private void UpdateLanguage()
        { 
            LangList.Clear();
            string path = Path.Combine(Environment.CurrentDirectory, "lang", "languagefileinfo.json");
            if (File.Exists(path))
            {
                var list = System.Text.Json.JsonSerializer.Deserialize<IList<StarryEdge.Core.Models.LanguageFileInfoModel>>(File.ReadAllText(path));
                foreach ( var item in list )
                {
                    LangList.Add(new LanguageImageModel() { Source = new BitmapImage(new Uri(Path.Combine(Environment.CurrentDirectory, item.ImagePath))), Lang = item.Lang });
                }
                return;
            }
            LangList.Add(new LanguageImageModel() { Source = new BitmapImage(new Uri(Path.Combine(Environment.CurrentDirectory, "Resource\\Flag\\cn.png"))), Lang = "cn" });
            LangList.Add(new LanguageImageModel() { Source = new BitmapImage(new Uri(Path.Combine(Environment.CurrentDirectory, "Resource\\Flag\\en.png"))), Lang = "en" });
        }
    }
}
